package com.topnav.mc.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.js.lib.result.Result;
import com.topnav.mc.admin.entity.GbCodeCity;
import com.topnav.mc.admin.entity.bean.GbCodeCityBean;
import com.topnav.mc.admin.entity.wrapper.GbCodeCityWrapper;
import com.topnav.mc.admin.service.IGbCodeCityService;
import com.topnav.mc.base.mc.McLbController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "admin/code/city", tags = "国标编码-行政区域")
@RestController
@CrossOrigin
@RequestMapping("admin/code/city")
public class GbCodeCityController extends McLbController<GbCodeCity, GbCodeCityBean, GbCodeCity, IGbCodeCityService, GbCodeCityWrapper> {
    @Autowired
    private IGbCodeCityService gbCodeCityService;

    @GetMapping("/query/find")
    @ResponseBody
    public Result find(String parentId){
        LambdaQueryWrapper<GbCodeCity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(GbCodeCity::getId);
        List<GbCodeCityBean> list = gbCodeCityService.listInfo(wrapper);
        Map<String,GbCodeCityBean> map = new HashMap<String,GbCodeCityBean>();
        for(GbCodeCityBean bean  : list){
            if (bean.getHasChildren()){
                map.put(bean.getId(),bean);
            }
        }

        List<GbCodeCityBean> resultList = new ArrayList<>();
        GbCodeCityBean parent;
        for(GbCodeCityBean bean  : list){
            if ("0".equals(bean.getParentId())){
                resultList.add(bean);
                parent = bean;
            }else {
                parent = map.get(bean.getParentId());
                if (parent != null){
                    if (parent.getChildren() == null){
                        List<GbCodeCityBean> children = new ArrayList<>();
                        parent.setChildren(children);
                    }
                    parent.getChildren().add(bean);
                }
            }
        }

        return Result.ok(resultList);
    }

    private void dds(){

    }
}
